$("#registerBtn").click((e) => {
    e.preventDefault();
    register();
})

$("#sendCode").click((e) => {
    e.preventDefault();
    sendCode();
})

const titleMap =  {
    'email': '邮箱',
    'password': '密码',
    'repassword': '重复密码',
    'code': '验证码',
}

function register() {
    let array = $("#registerForm").serializeArray();
    let obj = array.reduce((res, item) => {
        res[item['name']] = item['value'];
        return res;
    }, {});
//    console.log(array);
//    console.log(obj);

    for (let key of Object.keys(obj)) {
        if (!obj[key]) {
            alert(`${titleMap[key]}不能为空`);
            return ;
        }
    }

    let url = `/api/user/register/${obj.email}/${obj.password}/${obj.code}`;
//    url = 'http://localhost:8080' + url;
    $.get(url, (data) => {
        console.log(data);
        if (data.status != 0) {
            alert(data.message);
        } else {
            alert("注册成功！");
            window.location.href = 'login.html';
        }
    });
}


function sendCode() {
  let array = $("#registerForm").serializeArray();
    let obj = array.reduce((res, item) => {
        res[item['name']] = item['value'];
        return res;
    }, {});

    if (!obj.email) {
        alert('请输入邮箱！')
    }

    let url = `/api/code/create/${obj.email}`;
    $.get(url, (data) => {
        console.log(data);
    })

    sendCodeCountDown(60);
}

function sendCodeCountDown(remainCount) {
    if (remainCount > 0) {
        $("#sendCode").attr("disabled", "disabled");
        $("#sendCode").text(`已发送，剩余${remainCount}秒可以重发`);
        setTimeout(() => {
            --remainCount;
            sendCodeCountDown(remainCount);
        }, 1000);
    } else {
        $("#sendCode").removeAttr("disabled");
        $("#sendCode").text(`发送验证码`);
    }
}